<script setup>
import courseApi from '@/api/courseApi.js'
import coachApi from '@/api/coachApi.js'
import {reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import ReserveSign from './ReserveSign.vue'

//分页参数
const pageInfo = ref({
    page:1,
    limit:10,
    total:0
})

//查询教练
const coachs = ref([])
loadCoachs()
function loadCoachs() {
    coachApi.search().then(result=>{
        console.log("教练：",result)
        coachs.value = result.data
    })
}

// 课程列表的数据源
const courses = ref([])
loadCourses()
//查询课程列表
function loadCourses() {
    courseApi.search(pageInfo.value).then(result=>{
        console.log('课程：',result)
        courses.value = result.data.list
        pageInfo.value.total = result.data.total
    }).catch(error=>{
        // ElMessage.error('服务器忙，请稍后再试')
    })
}

//查询按钮执行查询操作
function onSearch() {
    pageInfo.page = 1
    loadCourses()
}

//接收表格行中scope.row.photo的值，对其进行处理
function getImgUrl(row) {
    console.log("图片地址",row)
    return row
}

const baseURL = 'http://localhost:9001'

function getUploadURL(){
    return baseURL + "/upload/savePic"
}
function handleAddAvatarSuccess(res){// 应该是上传的返回结果能自动注入把
    console.log(res.data)
    addCourse.value.photo = res.data
    console.log(addCourse.value.photo)
}
function handleEditAvatarSuccess(res){// 应该是上传的返回结果能自动注入把
    console.log("===========handleEditAvatarSuccess=========",res.data)
    editCourse.value.photo = res.data
    console.log(editCourse.value.photo)
}

const addVisible = ref(false)
const addCourse = ref({})
//绑定创建课程按钮，显示弹框
function showAdd() {
    addVisible.value = true
}
//添加课程
function handleAdd() {
    courseApi.add(addCourse.value).then(result=>{//ref创建的响应式对象需要通过.value才能访问到其实际存储的值
        if(result.code == 200) {
            //添加成功
            ElMessage.success('课程添加成功')
            //关闭弹框
            addVisible.value = false
            //清空弹框
            addCourse.value = {}
            //重新加载课程列表
            loadCoachs()
        } else {
            //添加失败
            ElMessage.error(result.msg)
            //关闭弹框
            addVisible.value = false
            //清空弹框
            addCourse.value = {}
        }
    }).catch(error=>{
        //添加失败
        ElMessage.error('服务器忙，添加失败')
    })
}

const reserveVisible = ref(false)
// 显示预约的学员
function showReserve(row) {
    reserveVisible.value = true
    editCourse.value = JSON.parse(JSON.stringify(row)); // 深拷贝行数据，确保包含id
}

const editVisible = ref(false)
const editCourse = ref({})
//编辑课程（回显）
function showEdit(row) {
    console.log("课程信息：",row)
    editVisible.value = true
    editCourse.value = JSON.parse(JSON.stringify(row))
}
//编辑课程
function handleEdit() {
    courseApi.edit(editCourse.value).then(result=>{
        if(result.code == 200) {
            //修改成功
            ElMessage.success('课程修改成功')
            //关闭弹框
            editVisible .value = false
            //重新加载课程列表
            loadCourses()
        } else {
            //修改失败
            ElMessage.error(result.msg)
            //关闭弹框
            editVisible.value = false
        }
    }).catch(error=>{
        //修改失败
        ElMessage.error('服务器忙，修改失败')
    })
}

//删除课程
function handleRemove(row) {

//     ElMessageBox.confirm(
//     '您确定删除该课程吗?',
//     '警告',
//     {
//       confirmButtonText: '删除',
//       cancelButtonText: '取消',
//       type: 'warning',
//     }
//   ).then(() => {

        courseApi.remove(row.id).then(result=>{
            if(result.code == 200) {
                //删除成功
                ElMessage.success('课程删除成功')
                //加载页面
                loadCourses()
            } else {
                //删除失败
                ElMessage.error(result.msg)
            }
        }).catch(error=>{
            //删除失败
            ElMessage.error('服务器忙，删除失败')
        })
    // })
}



</script>

<template>
    <div class="content">
        <!-- 搜索栏 -->
        <el-form :model="pageInfo" :inline="true">
            <el-form-item label="课程名称" :label-width="80">
                <el-input v-model="pageInfo.name" clearable placeholder="请输入课程名字"/>
            </el-form-item>
            <el-form-item label="授课教练" :label-width="80">
                <el-select
                    v-model="pageInfo.coachId"
                    value-key="id"
                    placeholder="请选择课程教练"
                    style="width: 240px"
                    clearable
                    >
                    <el-option
                        v-for="item in coachs"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <!-- 查询按钮 -->
            <el-form-item>
                <el-button type="primary" @click="onSearch"><el-icon><Search></Search></el-icon></el-button>
            </el-form-item>
        </el-form>
        <!-- 创建课程按钮 -->
        <div class="bar">
            <el-button type="success" @click="showAdd" >创建课程</el-button>
        </div>
        <!-- 课程列表 -->
        <el-table :data="courses" :stripe="true" :border="true" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="photo" label="照片" >
                <template #default="scope">
                    <img :src="getImgUrl(scope.row.photo)" style="max-height: 60px; max-width: 120px;"/>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="课程名" />
            <!-- 
            后端通过<resultMap>的<association>配置：
            1. 先查询课程表和预约表，得到课程基本信息 + 预约数
            2. 自动根据课程的coach_id，调用CoachMapper.selectByPrimaryKey方法查询对应的教练信息（返回Coach类对象）
            3. 最终将查询到的Coach对象赋值给CourseVO的coach属性，即此时CourseVO的coach属性是一个完整的Coach类对象
            前端数据访问层面：prop需要指向具体属性路径，即coach.name
            -->
            <el-table-column prop="coach.name" label="教练" :formatter="fmtCoach"/>
            <el-table-column prop="room" label="教室" />
            <el-table-column prop="time" label="时间" width="180" />
            <el-table-column prop="length" label="时长" width="100"/>
            <el-table-column prop="reserveCount" label="预约人数" width="100"/>
            <el-table-column prop="maxCount" label="最大人数" width="100"/>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" type="primary"
                        @click="showReserve(scope.row)">学员</el-button> 
                    <el-button size="small" type="success"
                        @click="showEdit(scope.row)">编辑</el-button> 
                    <el-button size="small" type="danger"
                        @click="handleRemove(scope.row)">删除</el-button> 
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页插件 -->
        <el-pagination class="page" v-model:current-page="pageInfo.page" v-model:page-size="pageInfo.limit"
            :total="pageInfo.total" :page-sizes="[10, 20, 50, 100]" :background="true"
            layout="total, sizes, prev, pager, next, jumper" @change="loadCourses" />
    </div>

    <!-- 添加的弹窗 -->
    <el-dialog v-model="addVisible" title="创建新课程" width="600">
        <el-form :model="addCourse">
            <el-form-item label="照片" :label-width="80">
                <el-upload
                    class="avatar-uploader"
                    :action="getUploadURL()"
                    :show-file-list="false"
                    :on-success="handleAddAvatarSuccess"
                >
                    <img v-if="addCourse.photo" :src="getImgUrl(addCourse.photo)" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="课程名称" :label-width="80">
                <el-input v-model="addCourse.name" placeholder="请输入课程名字"/>
            </el-form-item>
            <el-form-item label="授课教练" :label-width="80">
                <el-select
                    v-model="addCourse.coachId"
                    value-key="id"
                    placeholder="请选择课程教练"
                    style="width: 240px"
                    >
                    <el-option
                        v-for="item in coachs"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="上课教室" :label-width="80">
                <el-col :span="10">
                    <el-input v-model="addCourse.room" placeholder="请输入上课教室"/>
                </el-col>
                <el-col :span="4" style="text-align: center;">
                    <span class="text-gray-500">最大人数</span>
                </el-col>
                <el-col :span="8">
                    <el-input-number v-model="addCourse.maxCount" :min="10" :max="120" :step="10" placeholder="最大人数"/>
                </el-col>
            </el-form-item>
            <el-form-item label="上课时间" :label-width="80">
                <el-col :span="10">
                    <el-date-picker
                        v-model="addCourse.time"
                        editable
                        type="datetime"
                        placeholder="上课时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width:100%;"
                    /> 
                </el-col>
                <el-col :span="4" style="text-align: center;">
                    <span class="text-gray-500">课程时长</span>
                </el-col>
                <el-col :span="8">
                    <el-input-number v-model="addCourse.length" :min="10" :max="120" :step="10" placeholder="课程时长"/>
                </el-col>
                <el-col :span="2" style="text-align: center;">
                    <span class="text-gray-500">分钟</span>
                </el-col>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd">
                    创建
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 编辑的弹窗 -->
    <el-dialog v-model="editVisible" title="编辑课程" width="600">
        <el-form :model="editCourse">
            <el-form-item label="照片" :label-width="80">
                <el-upload
                    class="avatar-uploader"
                    :action="getUploadURL()"
                    :show-file-list="false"
                    :on-success="handleEditAvatarSuccess"
                >
                    <img v-if="editCourse.photo" :src="getImgUrl(editCourse.photo)" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="课程名称" :label-width="80">
                <el-input v-model="editCourse.name" placeholder="请输入课程名字"/>
            </el-form-item>
            <el-form-item label="授课教练" :label-width="80">
                <el-select
                    v-model="editCourse.coachId"
                    value-key="id"
                    placeholder="请选择课程教练"
                    style="width: 240px"
                    >
                    <el-option
                        v-for="item in coachs"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="上课教室" :label-width="80">
                <el-col :span="10">
                    <el-input v-model="editCourse.room" placeholder="请输入上课教室"/>
                </el-col>
                <el-col :span="4" style="text-align: center;">
                    <span class="text-gray-500">最大人数</span>
                </el-col>
                <el-col :span="8">
                    <el-input-number v-model="editCourse.maxCount" :min="10" :max="120" :step="10" placeholder="最大人数"/>
                </el-col>
            </el-form-item>
            <el-form-item label="上课时间" :label-width="80">
                <el-col :span="10">
                    <el-date-picker
                        v-model="editCourse.time"
                        editable
                        type="datetime"
                        placeholder="上课时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width:100%;"
                    /> 
                </el-col>
                <el-col :span="4" style="text-align: center;">
                    <span class="text-gray-500">课程时长</span>
                </el-col>
                <el-col :span="8">
                    <el-input-number v-model="editCourse.length" :min="10" :max="120" :step="10" placeholder="课程时长"/>
                </el-col>
                <el-col :span="2" style="text-align: center;">
                    <span class="text-gray-500">分钟</span>
                </el-col>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editVisible = false">取消</el-button>
                <el-button type="primary" @click="handleEdit">
                    编辑
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="reserveVisible" title="预约学员" width="60%">
        <ReserveSign v-model="editCourse"></ReserveSign>
    </el-dialog>
</template>

<style >

</style>